package com.huilian.iotbox.admin.controller;

import com.alibaba.fastjson.JSON;
import com.huilian.iotbox.admin.service.FileService;
import com.huilian.iotbox.admin.service.QiNiuService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.controller.BaseController;
import com.huilian.iotbox.data.dto.UpLoadDto;
import com.huilian.iotbox.data.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author mineChen
 * @Date: 2020/4/15 17:42
 */
@RequestMapping("/api/file")
@Slf4j
@RestController
public class QiNiuController extends BaseController {
    @Resource
    private QiNiuService qiNiuService;
    @Resource
    private FileService fileService;
    @Autowired
    private UserService userService;

    /**
     * 上传图片到七牛
     */
    @PostMapping("/uploadQiNiu")
    public ServerResponse uploadQiNiu(@RequestBody MultipartFile image, @Param(value = "type") Integer type, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        log.info("uploadQiNiu：" + JSON.toJSONString(userInfo));
        return qiNiuService.fileupload(image, type);
    }

    @PostMapping("/uploadImage")
    public ServerResponse uploadImage(@RequestBody MultipartFile image, @Param(value = "type") Integer type, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        log.info("uploadImage：" + JSON.toJSONString(userInfo));
        return qiNiuService.uploadImage(image, type);
    }

    @PostMapping("/deleteByFileNameToFTP")
    public ServerResponse deleteByFileNameToFTP(@RequestBody UpLoadDto upLoadDto, HttpServletRequest request) throws IOException {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        log.info("deleteByFileNameToFTP：" + JSON.toJSONString(userInfo));
        if(StringUtils.isEmpty(userInfo)){
            return ServerResponse.createByErrorMessage("获取商户信息失败");
        }
        return qiNiuService.deleteByFileNameToFTP(upLoadDto.getFileName());
    }

    @PostMapping("/download/{fileName:.+}")
    public void download(@PathVariable("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        log.info("download：" + JSON.toJSONString(userInfo));
        fileService.download(fileName, response);
    }
}
